<template>
  <div class="ai-thinking-generator">
    <a-card title="AI批阅思路生成器" :bordered="false">
      <div class="layout-container">
        <!-- 上方：输入表单区域 -->
        <div class="form-container">
          <a-form layout="vertical">
            <a-form-item label="文件信息" required>
              <a-alert type="info" show-icon>
                <template #message>已上传文件</template>
                <template #description>
                  <p>文件路径: {{ fileUrl || '暂无文件' }}</p>
                  <p v-if="fileUrl">文件名: {{ getFilenameFromUrl(fileUrl) }}</p>
                </template>
              </a-alert>
            </a-form-item>
            
            <a-form-item label="教师关注方向" required>
              <a-alert
                message="关注方向说明"
                description="请输入教师重点关注的内容，如知识点掌握情况、解题思路、答题规范等。这将指导AI生成更有针对性的批阅思路。"
                type="info"
                show-icon
                style="margin-bottom: 8px;"
              />
              <a-textarea
                :value="params.focusDirections"
                @input="handleTextareaInput"
                @composition-start="handleComposition"
                @composition-end="handleComposition"  
                @blur="handleTextareaBlur"
                placeholder="请输入教师关注方向，如重点考察知识点、评分标准等"
                :rows="6"
                :disabled="loading"
                class="textarea-input"
                :status="params.focusDirections ? '' : 'error'"
              />
              <div v-if="!params.focusDirections" style="color: #ff4d4f; font-size: 12px; margin-top: 4px;">
                请输入教师关注方向
              </div>
              <div v-else style="margin-top: 5px; font-size: 12px; color: #999;">
                当前字符数: {{ params.focusDirections.length }}
              </div>
            </a-form-item>

            <!-- AI模型相关设置 -->
            <a-divider orientation="left">AI模型设置（选填）</a-divider>
            
            <a-form-item label="AI模型">
              <a-select
                :value="params.modelName"
                @update:value="updateModelName"
                placeholder="请选择AI模型"
                :disabled="loading"
              >
                <a-select-option value="gpt-3.5-turbo">GPT-3.5 Turbo</a-select-option>
                <a-select-option value="gpt-4">GPT-4</a-select-option>
                <a-select-option value="qwen-turbo">通义千问</a-select-option>
                <a-select-option value="glm-4">智谱GLM-4</a-select-option>
                <a-select-option value="baichuan-turbo">百川大模型</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="温度参数">
                  <div>
                    <a-slider
                      :value="params.temperature"
                      @update:value="updateTemperature"
                      :min="0"
                      :max="2"
                      :step="0.1"
                      :disabled="loading"
                    />
                    <div class="slider-value">当前值: {{ params.temperature }}</div>
                  </div>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="最大Token数">
                  <a-input-number
                    :value="params.maxTokens"
                    @update:value="updateMaxTokens"
                    :min="100"
                    :max="4000"
                    :step="100"
                    placeholder="默认: 1000"
                    :disabled="loading"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item>
              <a-space>
                <a-button
                  type="primary"
                  :loading="loading"
                  :disabled="!isValid"
                  @click="generateAIThinking"
                  size="large"
                  class="generate-button"
                >
                  生成AI批阅思路
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        
        <a-divider />
        
        <!-- 下方：结果展示区域 -->
        <div class="result-container">
          <div class="result-header">
            <h3>AI批阅思路结果</h3>
            <div class="progress-container" v-if="loading">
              <a-tag color="processing">生成中: {{ Math.round(completionPercentage) }}%</a-tag>
              <a-progress 
                :percent="completionPercentage" 
                :status="loading ? 'active' : 'normal'" 
                size="small"
              />
            </div>
          </div>
          
          <div class="thinking-process-container">
            <div class="thinking-process" v-if="streamResult || result || loading">
              <a-spin :spinning="loading && !streamResult && !result">
                <div class="thinking-content">
                  <div 
                    v-if="streamResult || result" 
                    class="content-text" 
                    v-html="streamResult ? sanitizedStreamResult : sanitizedResult" 
                  />
                  <div v-else class="content-placeholder">AI思考中，请稍候...</div>
                </div>
              </a-spin>
            </div>
            <a-empty v-else description="点击『生成AI批阅思路』按钮开始生成" />
            
            <div class="result-actions" v-if="result || streamResult">
              <a-space>
                <a-button type="primary" @click="confirmResult">
                  <template #icon><check-outlined /></template>
                  确认使用
                </a-button>
                <a-button @click="regenerate">
                  <template #icon><sync-outlined /></template>
                  重新生成
                </a-button>
                <a-button @click="copyToClipboard">
                  <template #icon><copy-outlined /></template>
                  复制结果
                </a-button>
              </a-space>
            </div>
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts">
import { ref, reactive, computed, watch, defineComponent, onBeforeUnmount } from 'vue'
import { message } from 'ant-design-vue'
import { generateAIThinkingSimple } from '@/api/assignment'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { CheckOutlined, SyncOutlined, CopyOutlined } from '@ant-design/icons-vue'

export default defineComponent({
  name: 'AIThinkingStreamGenerator',
  components: { 
    CheckOutlined, 
    SyncOutlined, 
    CopyOutlined 
  },
  props: {
    initialContent: {
      type: String,
      default: ''
    },
    initialAiPromptTemplate: {
      type: String,
      default: ''
    },
    initialFocusDirections: {
      type: String,
      default: ''
    },
    initialResult: {
      type: String,
      default: ''
    },
    fileUrl: {
      type: String,
      default: ''
    },
    initialModelName: {
      type: String,
      default: ''
    },
    initialTemperature: {
      type: Number,
      default: 0.7
    },
    initialMaxTokens: {
      type: Number,
      default: 1000
    }
  },
  emits: ['update', 'confirm', 'generate'],
  setup(props, { emit }) {
    // 参数状态
    const params = reactive({
      focusDirections: props.initialFocusDirections ? String(props.initialFocusDirections) : '',
      modelName: props.initialModelName || 'gpt-3.5-turbo',
      temperature: props.initialTemperature || 0.7,
      maxTokens: props.initialMaxTokens || 1000
    })

    console.log('[AIThinkingStreamGenerator] 初始化参数:', {
      initialFocusDirections: props.initialFocusDirections,
      currentFocusDirections: params.focusDirections,
      currentFocusDirectionsType: typeof params.focusDirections,
      fileUrl: props.fileUrl
    })

    // 监听初始关注方向的变化
    watch(() => props.initialFocusDirections, (newVal) => {
      if (newVal) {
        console.log('[AIThinkingStreamGenerator] 检测到initialFocusDirections变化:', newVal)
        params.focusDirections = String(newVal)
        // 确保同步到父组件
        emit('generate', params.focusDirections)
      }
    }, { immediate: true })
    
    // 监听focusDirections的变化，同步到父组件
    watch(() => params.focusDirections, (newVal, oldVal) => {
      if (newVal !== oldVal) {
        // 确保传递的是字符串
        const safeValue = typeof newVal === 'string' ? newVal : String(newVal || '');
        console.log('[AIThinkingStreamGenerator] focusDirections 已更新:', safeValue);
        
        // 当值变化时通知父组件
        emit('generate', safeValue);
      }
    }, { deep: true })

    // 更新关注方向的处理函数 
    const updateFocusDirections = (event: any) => {
      // 处理不同类型的事件输入
      let safeValue = '';
      
      // 如果是CompositionEvent或FocusEvent事件对象
      if (event && typeof event === 'object') {
        if (event.target && 'value' in event.target) {
          // 从事件对象的target.value中提取值
          safeValue = String(event.target.value || '');
        } else if (event instanceof Event) {
          // 其他类型的事件对象，尝试从当前textarea中获取值
          const textarea = document.querySelector('.textarea-input textarea');
          if (textarea && textarea instanceof HTMLTextAreaElement) {
            safeValue = textarea.value;
          }
        } else {
          // 其他对象类型，尝试转换为字符串
          safeValue = String(event || '');
        }
      } else if (typeof event === 'string') {
        // 直接是字符串
        safeValue = event;
      } else {
        // 其他类型，转为字符串
        safeValue = String(event || '');
      }
      
      console.log('[AIThinkingStreamGenerator] 处理后的教师关注方向:', safeValue);
      
      // 更新参数
      params.focusDirections = safeValue;
      
      // 通知父组件，确保传递的是字符串
      emit('generate', safeValue);
    }
    
    // 更新AI模型
    const updateModelName = (val: string) => {
      params.modelName = val
    }
    
    // 更新温度参数
    const updateTemperature = (val: number) => {
      params.temperature = val
    }
    
    // 更新最大Token数
    const updateMaxTokens = (val: number) => {
      params.maxTokens = val
    }

    // 检查参数是否有效
    const isValid = computed(() => {
      // 只要有文件URL就允许生成
      return !!props.fileUrl;
    })

    // 返回结果
    const result = ref<string>(props.initialResult)
    // 用于显示的结果
    const streamResult = ref<string>(props.initialResult)
    // 加载状态
    const loading = ref<boolean>(false)
    // 进度百分比
    const completionPercentage = ref<number>(0)

    // 监听initialResult的变化，确保编辑时能回显
    watch(() => props.initialResult, (newVal) => {
      if (newVal) {
        console.log('[AIThinkingStreamGenerator] 检测到initialResult变化:', newVal.substring(0, 50) + '...')
        result.value = newVal
        streamResult.value = newVal
      }
    }, { immediate: true })

    // 转换Markdown为HTML并进行安全过滤
    const sanitizedResult = computed(() => {
      if (!result.value) return ''
      try {
        const html = marked.parse(result.value) as string
        return DOMPurify.sanitize(html)
      } catch (error) {
        console.error('Markdown解析错误', error)
        return result.value
      }
    })

    // 流式结果的Markdown转换和安全过滤（保留此计算属性用于显示）
    const sanitizedStreamResult = computed(() => {
      if (!streamResult.value) return ''
      try {
        const html = marked.parse(streamResult.value) as string
        return DOMPurify.sanitize(html)
      } catch (error) {
        console.error('Markdown解析错误', error)
        return streamResult.value
      }
    })

    // 监听结果变化，触发更新事件
    watch(result, (newVal) => {
      emit('update', newVal)
    })

    // 模拟进度动画
    let progressTimer: number | null = null;
    
    const startProgressAnimation = () => {
      // 重置进度
      completionPercentage.value = 0;
      
      // 清除可能存在的旧计时器
      if (progressTimer) {
        clearInterval(progressTimer);
      }
      
      // 创建新计时器，模拟进度增长
      progressTimer = window.setInterval(() => {
        if (completionPercentage.value < 90) {
          // 进度增长速度随着进度增加而减缓
          const increment = (100 - completionPercentage.value) / 50;
          completionPercentage.value += increment;
        } else if (!loading.value) {
          // 如果加载完成，设为100%
          completionPercentage.value = 100;
          if (progressTimer) {
            clearInterval(progressTimer);
            progressTimer = null;
          }
        }
      }, 500);
    };
    
    const stopProgressAnimation = () => {
      if (progressTimer) {
        clearInterval(progressTimer);
        progressTimer = null;
      }
      completionPercentage.value = 100;
    };
    
    // 组件卸载前清理计时器
    onBeforeUnmount(() => {
      if (progressTimer) {
        clearInterval(progressTimer);
      }
    });

    // 生成AI批阅思路
    const generateAIThinking = async () => {
      if (!props.fileUrl) {
        message.warning('请确保已上传文件')
        return
      }
      
      // 尝试通过DOM获取最新的输入值（最可靠的方式）
      let currentValue = params.focusDirections || '';
      const textareaElement = document.querySelector('.ai-thinking-generator .textarea-input textarea');
      if (textareaElement && textareaElement instanceof HTMLTextAreaElement) {
        const domValue = textareaElement.value;
        if (domValue) {
          console.log('[AIThinkingStreamGenerator] 生成前通过DOM获取到值:', domValue);
          currentValue = domValue;
          params.focusDirections = domValue; // 更新状态
          // 立即通知父组件
          emit('generate', domValue);
        }
      }

      // 确保教师关注方向有内容 - 安全处理字符串
      if (!currentValue || currentValue.trim() === '') {
        message.warning('请输入教师关注方向')
        return
      }

      try {
        loading.value = true
        streamResult.value = '' // 清空显示结果
        
        // 显示请求开始提示
        message.loading({ content: '正在生成AI批阅思路...', key: 'aiThinking', duration: 0 })
        
        // 开始模拟进度动画
        startProgressAnimation()
        
        // 先触发generate事件，将当前focusDirections传递给父组件
        emit('generate', params.focusDirections)
        
        // 调用接口，传递所有参数
        const apiParams = {
          filePath: props.fileUrl, 
          focusDirections: currentValue.trim(),
          modelName: params.modelName,
          temperature: params.temperature,
          maxTokens: params.maxTokens
        }
        
        console.log('[AIThinkingStreamGenerator] 发送API请求:', {
          filePath: apiParams.filePath,
          focusDirections: apiParams.focusDirections.substring(0, 20) + '...',
          modelName: apiParams.modelName
        })
        
        try {
          // 普通请求调用
          const responseText = await generateAIThinkingSimple(apiParams);
          
          if (responseText) {
            // 设置结果
            streamResult.value = responseText;
            result.value = responseText;
            
            // 请求成功后处理
            message.success({ content: 'AI批阅思路生成成功', key: 'aiThinking' });
          } else {
            throw new Error('服务器返回数据为空');
          }
        } catch (callError: any) {
          console.error('[AIThinkingStreamGenerator] API调用失败:', callError);
          throw callError; // 往上传递错误
        }
      } catch (error: any) {
        console.error('[AIThinkingStreamGenerator] 请求失败:', error);
        message.error({ content: `请求失败: ${error.message || '未知错误'}`, key: 'aiThinking' });
        // 如果失败但没有内容，添加一个错误提示
        if (!streamResult.value) {
          streamResult.value = '获取AI批阅思路失败，请重试。';
        }
      } finally {
        loading.value = false;
        stopProgressAnimation();
      }
    }
    
    // 重新生成
    const regenerate = () => {
      if (!loading.value) {
        result.value = ''
        streamResult.value = ''
        generateAIThinking()
      }
    }
    
    // 确认使用当前结果
    const confirmResult = () => {
      // 在确认前，尝试获取最新的教师关注方向内容
      const textareaElement = document.querySelector('.ai-thinking-generator .textarea-input textarea');
      if (textareaElement && textareaElement instanceof HTMLTextAreaElement) {
        // 如果通过DOM能获取到值，则优先更新
        const domValue = textareaElement.value;
        if (domValue && domValue !== params.focusDirections) {
          console.log('[AIThinkingStreamGenerator] 通过DOM获取到最新值:', domValue);
          params.focusDirections = domValue;
        }
      }
      
      // 安全处理params.focusDirections
      const safeDirections = typeof params.focusDirections === 'string' 
        ? params.focusDirections 
        : String(params.focusDirections || '');
      
      // 获取有效的AI批阅思路结果，优先使用生成的结果，其次使用初始值
      const aiThinkingResult = result.value || streamResult.value || props.initialResult || '';
      
      const resultData = {
        aiThinkingProcess: aiThinkingResult,
        focusDirections: safeDirections,
        modelName: params.modelName,
        temperature: params.temperature,
        maxTokens: params.maxTokens
      }
      
      console.log('【AIThinkingStreamGenerator】确认时传递数据:', {
        focusDirections: safeDirections,
        hasValue: safeDirections ? '有值' : '无值',
        aiThinkingProcessLength: aiThinkingResult ? aiThinkingResult.length : 0
      })
      
      // 先发送generate事件，确保focusDirections被更新
      emit('generate', safeDirections)
      
      // 传递AI批阅思路结果和教师关注方向给父组件
      emit('confirm', resultData)
      message.success('已确认使用当前AI批阅思路')
    }
    
    // 复制结果到剪贴板
    const copyToClipboard = () => {
      // 获取有效的结果内容
      const contentToCopy = result.value || streamResult.value;
      
      if (contentToCopy) {
        navigator.clipboard.writeText(contentToCopy)
          .then(() => message.success('已复制到剪贴板'))
          .catch(_err => {
            message.error('复制失败')
          })
      }
    }

    // 从URL中获取文件名
    const getFilenameFromUrl = (url: string) => {
      if (!url) return '';
      try {
        return url.split('/').pop() || '';
      } catch {
        return '';
      }
    }

    // 直接处理textarea的input事件
    const handleTextareaInput = (e: any) => {
      // 从事件中提取文本值
      let value = '';
      if (e && e.target && typeof e.target.value === 'string') {
        value = e.target.value;
      } else if (typeof e === 'string') {
        value = e;
      }
      
      if (value !== params.focusDirections) {
        params.focusDirections = value;
        emit('generate', value);
      }
    }
    
    // 处理中文输入法的合成事件
    const handleComposition = (e: any) => {
      if (e.type === 'compositionend') {
        // 输入法输入完成，获取最终值
        const value = e.target.value;
        params.focusDirections = value;
        emit('generate', value);
      }
    }
    
    // 处理焦点离开事件
    const handleTextareaBlur = (e: any) => {
      const value = e.target.value;
      params.focusDirections = value;
      emit('generate', value);
    }

    return {
      params,
      result,
      streamResult,
      loading,
      isValid,
      sanitizedResult,
      sanitizedStreamResult,
      generateAIThinking,
      regenerate,
      confirmResult,
      copyToClipboard,
      completionPercentage,
      getFilenameFromUrl,
      updateFocusDirections,
      updateModelName,
      updateTemperature,
      updateMaxTokens,
      handleTextareaInput,
      handleComposition,
      handleTextareaBlur
    }
  }
})
</script>

<style scoped>
.ai-thinking-generator {
  margin-bottom: 20px;
}

/* 竖屏排版布局 */
.layout-container {
  display: flex;
  flex-direction: column;
  min-height: 500px;
}

.form-container {
  width: 100%;
  margin-bottom: 24px;
}

.result-container {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.result-header {
  margin-bottom: 16px;
}

.result-header h3 {
  font-size: 18px;
  margin: 0 0 12px 0;
  color: #333;
}

.progress-container {
  margin-bottom: 16px;
}

.thinking-process-container {
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  min-height: 300px;
}

.thinking-process {
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.thinking-content {
  padding: 16px;
  background-color: #fff;
  flex: 1;
  overflow: auto;
  min-height: 250px;
}

.content-text {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.content-placeholder {
  color: #999;
  padding: 24px;
  text-align: center;
}

.result-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.textarea-input {
  border-radius: 4px;
  font-size: 14px;
  resize: none;
}

.generate-button {
  min-width: 140px;
}

.empty-result {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.slider-value {
  text-align: center;
  margin-top: 5px;
  color: #666;
}

/* Markdown样式 */
.content-text :deep(h1),
.content-text :deep(h2),
.content-text :deep(h3) {
  margin-top: 16px;
  margin-bottom: 8px;
}

.content-text :deep(p) {
  margin-bottom: 12px;
}

.content-text :deep(ul),
.content-text :deep(ol) {
  padding-left: 20px;
  margin-bottom: 12px;
}

.content-text :deep(pre) {
  background-color: #f0f0f0;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  margin-bottom: 12px;
}

.content-text :deep(code) {
  font-family: 'Courier New', Courier, monospace;
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 2px;
}

.content-text :deep(blockquote) {
  border-left: 4px solid #ddd;
  padding-left: 16px;
  margin-bottom: 12px;
  color: #666;
}

/* 适配移动端样式，保留原有的自适应逻辑 */
@media screen and (max-width: 768px) {
  .result-actions {
    flex-direction: column;
    align-items: center;
    gap: 8px;
  }
}
</style> 